package com.jxcq.tensquare.qa.interceptor;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author CalvinXCui
 * @date 2019- 10- 17 17:02
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {
//public class JWTInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过拦截器");
        //由于每个用户要求的角色权限都不一样，所以这里无论如何放行，具体能不能操作还是在具体操作中判断
        //拦截器只是负责把请求头中包含有token的令牌进行一个解析
        String authorization = request.getHeader("Authorization");
        if(StringUtils.isNotEmpty(authorization) && authorization.startsWith("Bearer ")){
            String token = authorization.substring(7);
            try {
                Claims claims = jwtUtil.parseJWT(token);
                String role = (String)claims.get("role");
                if(StringUtils.equals("admin",role)){
                    request.setAttribute("claims_admin",token);
                }
                if(StringUtils.equals("user",role)){
                    request.setAttribute("claims_user",token);
                }
            }catch (Exception e){
                throw new RuntimeException("令牌出错!");
            }
        }
        return true;
    }

}
